﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;

namespace QbservableCore.Serialization
{
    static internal class MethodCall
    {
        public static void BuildJson(MethodCallExpression node, ExpressionToJson state)
        {
            JContainer json = TranslationHelper.AppendJsonToCurrentAsArray(state);

            //----------------------- Previous Call ---------------------
            var firstArg = node.Arguments.FirstOrDefault();
            if (firstArg != null)
            {
                JContainer prev = state.CreateAndTransform(firstArg, state.JsonCurrent);
            }

            //----------------------- Current Call ---------------------
            json.AddProperty(Consts.Json.Name, node.Method.Name, state);
            json.AddProperty(Consts.Json.Category, node.NodeType, state);
            json.AddProperty(node.Type, state);

            var args = node.Arguments;//.Skip(1);
            json.AddParamsToJson(args, state);
        }

        public static void BuildExpression(
            JObject json, 
            Expression instanceExpression,
            IQbservableConvention convention)
        {
            string methodName = json.ExtractPropertyToKey(Consts.Json.Name, convention);
            Type methodType = json.ExtractPropertyType(convention);

            JArray prms = json.ExtractPropertyRaw<JArray>(Consts.Json.Params, convention);

            var prmTypes = from j in prms
                           let jObj = j as JObject
                           select jObj.ExtractPropertyType(convention);

            Type[] prmTypesArray = Enumerable.Concat(
                new Type[]{}, 
                prmTypes.ToArray()).ToArray();
            //json.
            //MethodInfo mi = methodType.GetMethod(methodName, );

            //MethodCallExpression mce = Expression.Call(instanceExpression, mi);
            //instanceExpression
        }
    }
}
